package com.cn.service.impl;

import com.cn.mapper.OrderMapper;
import com.cn.pojo.Order;
import com.cn.service.OrderService;
import com.cn.service.ProductService;
import com.cn.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ProductService productService;
    @Autowired
    private UserService userService;
    /**
     * 添加单个订单
     * @return 1表示成功，0表示失败
     */
    @Override
    public int addOrder(Order order) {
        //查询当前商品数量
        int count = productService.queryProductCount(order.getProductId());
        if (count < order.getCount()) {
            return 0;
        }
        //更新商品数量
        int newcount = count - order.getCount();
        int result = productService.setProductCount(order.getProductId(), newcount);
        if (result == 1) {
            return orderMapper.addOrder(order);
        }
        return 0;
    }
    /**
     * 根据用户名和商品名添加订单
     * @param username 用户名
     * @param productName 商品名
     * @param count 购买数量
     * @return 1表示成功，0表示失败
     */
    @Override
    public int addOrderByName(String username, String productName, int count) {
        int productId = productService.queryProductIdByName(productName);
        int userId = userService.queryUserIdByName(username);
        //查询当前商品数量
        int productCount = productService.queryProductCount(productId);
        if (productCount < count) {
            return 0;
        }
        //更新商品数量
        int newcount = productCount - count;
        int result = productService.setProductCount(productId, newcount);
        //封装订单对象
        Order order = new Order(null, userId, productId, count);
        if (result == 1) {
            return orderMapper.addOrder(order);
        }
        return 0;
    }
}
